﻿using System;
using System.Text;

namespace TSites.Utility.Random
{
	public class StringRandom : IRandom
	{
		private string _allowedChars = null;
		public string AllowedChars
		{
			get
			{
				if (_allowedChars == null || _allowedChars.Length == 0)
				{
					// default value
					_allowedChars = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%&()<>?-+=\|/";
				}
				return _allowedChars;
			}
			set { _allowedChars = value; }
		}
		
		#region IRandom Members

		public string Generate(int size)
		{
			// get const string
			string constString = AllowedChars;

			StringBuilder builder = new StringBuilder(size);
			int length = constString.Length;

			System.Random rand = new System.Random();
			for (int i = 0; i < size; i++)
			{
				builder.Append(constString[rand.Next(0, length)]);
			}
			return builder.ToString();
		}

		public byte[] GetBytes(int size)
		{
			// get const string
			string constString = AllowedChars;

			byte[] buffer = new byte[size];
			int length = constString.Length;

			System.Random rand = new System.Random();
			for (int i = 0; i < size; i++)
			{
				buffer[i] = (byte)constString[rand.Next(0, length)];
			}
			return buffer;
		}

		#endregion
	}
}
